<?php

class Common_Controller_Main extends Zend_Controller_Action {

    public $rola = 'admin';

    /**
     *
     * @var Common_Auth_Adapter_DbTable
     */
    public $adapter = null;

    /**
     *
     * @var Zend_Auth
     */
    public $auth = null;

    /**
     *
     * @var array
     */
    protected $json = array(
        'body' => '',
        'id' => '',
        'callback' => '',
    );

    /**
     *
     * @var bool
     */
    public $postOff = false;

    const MODEL_PREFIX = 'Application_Model_';
    const DBTABLE_PREFIX = 'Application_Model_DbTable';

    /**
     *
     * @var id
     */
    public $user = null;

    /**
     *
     * @var Zend_Db_Table_Row
     */
    public $userObject = null;

    /**
     *
     * @var Zend_Controller_Action_Helper_FlashMessenger
     */
    public $flashMessenger = null;

    /**
     *
     * @var Zend_Session_Namespace
     */
    public $addsSession = null;

    const ADDS_SESSION_NAME = 'addsSession';

    public function preDispatch() {
        
    }

    /**
     * 
     * @return Common_Controller_Helper_Content
     */
    public function getContentHelper() {
        return new Common_Controller_Helper_Content();
    }

    public function loginAction() {

        $this->_helper->layout()->setLayout('login');
        $this->view->form = new Application_Form_Login();

        if ($this->_request->isPost()) {
            $data = $this->_request->getPost();
            if ($this->view->form->isValid($data)) {
                if ($this->authIdentity($data['login'], $data['password'])) {
                    $this->redirect($this->view->url(array('module' => 'admin', 'action' => 'index'), null, true));
                }
            }
        }
    }

    public function logoutAction() {
        $this->noOut();
        $this->auth->clearIdentity();
        $this->redirect($this->view->url(array('module' => 'admin', 'action' => 'login'), null, true));
    }

    public function wylogujAction() {
        $this->noOut();
        $this->auth->clearIdentity();
        $this->redirect($this->view->url(array('module' => 'default', 'action' => 'logouted'), null, true));
    }

    public function init() {
        parent::init();

        $this->addsSession = new Zend_Session_Namespace(self::ADDS_SESSION_NAME);

        $this->adapter = new Common_Auth_Adapter_DbTable(
                        Zend_Db_Table::getDefaultAdapter(),
                        'users',
                        'login',
                        'password',
                        "MD5(CONCAT('"
                        . Zend_Registry::get('staticSalt')
                        . '\', ?)) and `active`=1 and `confirmed`=1 and `deleted`=0 and `rola`=' . Application_Model_Users::ROLA_GUEST . ''
        );

        $this->auth = Zend_Auth::getInstance();
        $this->flashMessenger = $this->view->flashMessenger = $this->_helper->FlashMessenger;

        $this->user = $this->view->user = $this->getLoggedUserId();
        if ($this->user != null) {
            $users = new Application_Model_Users();
            $this->userObject = $this->view->userObject = $users->getById($this->user);
        }
        $this->view->request = $this->_request;
                
        if ($this->_request instanceof Zend_Controller_Request_Http) {
            if (!$this->getAuthIdentity() && $this->_request->getActionName() != "login" && $this->_request->getModuleName() == "admin") {

                $this->redirect($this->view->url(array('module' => 'admin', 'action' => 'login'), null, true));
                exit();
            }
        }        
    }

    public function authIdentity($login, $passwd) {

        $this->adapter
                ->setIdentity($login)
                ->setCredential($passwd);
        $result = $this->auth->authenticate($this->adapter);

        if ($result->isValid()) {

            $userInfo = $this->getAuthObject();
            $authStorage = $this->auth->getStorage();
            $authStorage->write($userInfo);
            return $userInfo;
        }
        return false;
    }

    public function getAuthObject() {
        return $this->adapter->getResultRowObject(null, 'password');
    }

    /**
     * 
     * @return bool
     */
    public function getAuthIdentity() {

        return $this->auth->hasIdentity();
    }

    /**
     * 
     * @return null|array
     */
    public function getLoggedUserId() {
        if ($this->getAuthIdentity()) {
            $ob = $this->auth->getStorage()->read();

            return is_object($ob) ? $ob->id : null;
        } else {
            return null;
        }
    }

    public function addUser($data) {

        $users = new Application_Model_DbTable_Users();

        $data['password'] = md5(Zend_Registry::get('staticSalt') . $data['password']);

        $user = $users->insert($data);
        return $users->fetchRow('id=' . $user->id);
    }

    public function sendMail($data) {

        $config = Zend_Registry::get('mail');

        $mail = new Zend_Mail();
        $mail->setBodyText(strip_tags($data['body']));
        $mail->setBodyHtml($data['body']);
        $mail->setFrom($config['defaultFrom']['email']);

        if (isset($data['to']) && is_array($data['to'])) {
            foreach ($data['to'] as $kemail => $name) {
                $mail->addTo($kemail, $name);
            }
        }

        $mail->addTo($config['defaultFrom']['email']);
        $mail->setSubject(isset($data['subject']) ? $data['subject'] : 'subject not set');
        $mail->send();
    }

    public function log($msg, $extra = null) {
        $logger = Zend_Registry::get('logger');
        $logger->log($msg, 3, $extra);
    }

    public function addJsFile($name) {
        $this->view->headScript()->appendFile(
                '/js/' . $name, 'text/javascript', array()
        );
    }

    public function addJs($js, $attr = array()) {
        $this->view->headScript()->appendScript(
                $js, 'text/javascript', $attr
        );
    }

    public function addCss($name) {
        $this->view->headStyle()->appendStyle('css/' . $name, array());
    }

    public function addCssFile($name) {
        $this->view->headLink()->appendStylesheet('/css/' . $name);
    }

    public function setTitle($title) {
        $this->view->headTitle($title);
    }

    public function getPaginator($adapter) {
        $paginator = new Zend_Paginator($adapter);
        $paginator->setDefaultPageRange($this->getParam('range', '20'));
        $paginator->setDefaultItemCountPerPage($this->getParam('perpage', '25'));
        $paginator->setCurrentPageNumber($this->getParam('page', '1'));
        return $paginator;
    }

    public function noOut() {
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);
    }

    public function json($data) {
        return $this->_helper->json(array_merge($this->json, $data));
    }

    public function setmodelAction() {

        $this->noOut();
        $this->postOff = true;

        if ($this->_request->isXmlHttpRequest() && $this->_request->isPost() && $this->getParam('id', false)) {

            $table = $this->getParam('table', false);
            $model = self::MODEL_PREFIX . ucfirst($table);
            $inst = new $model();
            $item = $inst->table->fetchRow('id=' . $this->getParam('id'));

            $post = $this->_request->getPost();

            foreach ($post as $name => $value) {
                $item->{$name} = $value;
            }

            $item->save();

            echo $this->json(array(
                'status' => 'ok'
            ));
        }
    }

    public function postDispatch() {

        if ($this->postOff)
            return;
        if ($this->_request instanceof Zend_Controller_Request_Http) {
            if ($this->_request->isXmlHttpRequest()) {
                $this->noOut();
                echo $this->json(array_merge(array(
                            'body' => $this->view->render($this->getViewScript()),
                            'id' => 'content'
                                ), $this->_request->getPost()
                        )
                );
            }
        }
    }

}